var hostAddr = '';   /* tcp server host address */
var hostPort = 0;    /* tcp server host port */

function ArrayToString(fileData) {
  var dataString = "";
  for (var i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
  }

  return dataString;
}

var tcp = require('tcp');
var network = require('network');
var net = network.openNetWorkClient();

function createTcpClient() {
  var tcpSocket = tcp.createClient({
    host: hostAddr,
    port: hostPort,
    success: function () {
      console.log('tcp: tcp client connect success');
    },
    fail: function () {
      console.log('tcp: tcp client connect failed');
    }
  });

  // 测试接收数据
  tcpSocket.on('message', function (message) {
    if (!message) {
      throw new Error("tcp: [failed] tcp receive message");
    }
    console.log('tcp: [debug] on message: ' + ArrayToString(message));
  });

  // 测试socket异常
  tcpSocket.on('error', function (err) {
    console.log('tcp: tcp error ', err);
    tcpSocket.close();
    throw new Error("tcp: [failed] tcp on error");
  });

  tcpSocket.on('disconnect', function () {
    console.log('tcp: tcp disconnected');
  });

  // 测试发送数据

  tcpSocket.send({
    message: "this is amp test!",
    success: function () {
      console.log("tcp: [debug] send success");
    },
    fail: function () {
      console.log("tcp: send fail");
      throw new Error("tcp: [failed] tcp send fail");
    }
  });
}

var status = net.getStatus();
console.log('net status is: ' + status);

if (status == 'connect') {
  createTcpClient();
} else {
    net.on('connect', function () {
      createTcpClient();
    });
}